from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_x509_certificate
from cryptography.hazmat.primitives import hashes
from cryptography.x509.oid import NameOID
import datetime

# 加载 CA 证书
with open("ca.crt", "rb") as f:
    ca_cert_data = f.read()
ca_cert = x509.load_pem_x509_certificate(ca_cert_data, default_backend())

# 加载服务器证书
with open("server.crt", "rb") as f:
    server_cert_data = f.read()
server_cert = x509.load_pem_x509_certificate(server_cert_data, default_backend())

# 验证服务器证书是否由 CA 签发
try:
    ca_cert.public_key().verify(
        server_cert.signature,
        server_cert.tbs_certificate_bytes,
        padding.PKCS1v15(),
        server_cert.signature_hash_algorithm
    )
    print("Server certificate is valid and signed by the CA.")
except Exception as e:
    print(f"Server certificate validation failed: {e}")

# 打印 CA 证书信息
print("CA Certificate Information:")
print(f"Subject: {ca_cert.subject}")
print(f"Issuer: {ca_cert.issuer}")
print(f"Serial Number: {ca_cert.serial_number}")
print(f"Not Valid Before: {ca_cert.not_valid_before}")
print(f"Not Valid After: {ca_cert.not_valid_after}")

# 打印服务器证书信息
print("Server Certificate Information:")
print(f"Subject: {server_cert.subject}")
print(f"Issuer: {server_cert.issuer}")
print(f"Serial Number: {server_cert.serial_number}")
print(f"Not Valid Before: {server_cert.not_valid_before}")
print(f"Not Valid After: {server_cert.not_valid_after}")
